package com.youka.bussiness.common.bean;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.youka.bussiness.common.base.BaseEntity;
import com.youka.bussiness.common.utils.CollectionUtils;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
@ApiModel(value = "公共分页入参")
public class Page extends BaseEntity implements Serializable {
    //页码
    private int pageIndex;
    //每页展示数量
    private int pageSize;
    //总条数
    private int total;

    @ApiModelProperty(value = "排序参数", required = true, hidden = true)
    private String field;

    @ApiModelProperty(value = "是否升序", required = true, example = "asc-升序 desc-降序", hidden = true)
    private String order;

    private int begIndex;

    public Page(int pageIndex, int pageSize) {
        this.pageIndex = pageIndex;
        this.pageSize = pageSize;
    }

    public Page() {
        super();
    }

    public static <T> IPage<T> defaultPage(int pageIndex, int pageSize) {
        return new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageIndex, pageSize);
    }

    /**
     * 获取分页查询包装对象
     */
    public static QueryWrapper getPageWrapper(Page page) {
        QueryWrapper wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(page.getField()) && StringUtils.isNotEmpty(page.getOrder())) {
            if (SqlConst.ORDER_ASC.equalsIgnoreCase(page.getOrder())) {
                wrapper.orderByAsc(page.getField());
            } else {
                wrapper.orderByDesc(page.getField());
            }
        }
        return wrapper;
    }

    /**
     * 分页对象转换
     *
     * @param page
     * @param classOft
     * @param <T>
     * @param <S>
     * @return
     */
    public static <T, S> IPage<T> copyProperties(IPage<S> page, Class<T> classOft) {
        IPage<T> tPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<T> tList = CollectionUtils.convert(page.getRecords(), classOft);
        tPage.setRecords(tList);
        return tPage;
    }

    public int getBegIndex() {
        begIndex = (pageIndex - 1) * pageSize;
        begIndex = (begIndex >= 0) ? begIndex : 0;
        return begIndex;
    }

    public int getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    public int getPageSize() {
        return pageSize <= 0 ? 1000 : pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }
}
